<template>
    <el-container class="sys_resource_container">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent">
                </headerTemplate>
                <div class="card_content">
                    <el-row :gutter="10">
                        <el-col :span="4">
                            <ul id="resourceTree" class="ztree"></ul>
                        </el-col>
                        <el-col :span="20">
                            <vxeTableTemplate :data="resourceList" :options.sync="tableOptions"
                                              @event="handleTableEvent" />
                        </el-col>
                    </el-row>
                </div>
            </el-card>
        </el-main>
        <component-dialog dialog-drag :options="componentDialogOption" />
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import sysResourceApi from "@common/api/system/sysResourceApi";
import ResourceForm from "../dialog/resource/ResourceForm";
import MoveResource from "../dialog/resource/MoveResource";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "SysResource",
    data() {
        let $this = this;
        return {
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        label: '刷新树',
                        type: 'primary',
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            $this.initZTree();
                        },
                    },
                    {
                        id: "add",
                        label: '添加',
                        type: 'primary',
                        icon: "fa fa-plus",
                        show: true,
                        permission: 'res_add',
                        method: () => {
                            $this.openDialog();
                        },
                    },
                    {
                        id: "move",
                        label: '移动',
                        type: 'primary',
                        icon: "el-icon-rank",
                        show: true,
                        permission: 'res_move',
                        method: () => {
                            $this.moveDialog();
                        },
                    },
                ],
                toolbar_filter: [
                    { type: "checkbox", field: "searchForm.state", trueLabel: "1", falseLabel: "-1" }, ],
            },
            searchForm: {},
            ztreeSetting: {
                view: {
                    selectedMulti: false
                },
                check: {
                    enable: true
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                edit: {
                    enable: false
                }
            },
            root: {
                id: '-1',
                pId: '-999',
                name: '根节点'
            },
            zTreeData: [],
            parentId: '-1',
            resourceTree: [],
            resourceTreeData: [],
            resourceList: [],
            selection: [],
            tableOptions: {
                ref: 'resourceTable',
                container: '.sys_resource_container',
                multiSelect: true,
                columns: [
                    {
                        label: '图标',
                        prop: 'icon_url',
                        width: 60,
                        align: 'center',
                        formatter: (row) => {
                            if (row && row.icon_url && row.icon_url.indexOf('/pics/') !== -1) {
                                let url = window.configs.requestPrefix + row.icon_url;
                                return `<img src="${ url }" alt="" width="50">`;
                            } else {
                                return `<i class="${ row.icon_url }" style="color: ${ row.icon_color };"></i>`;
                            }
                        }
                    },
                    {
                        label: '资源名称',
                        prop: 'name'
                    },
                    {
                        label: '资源编码',
                        prop: 'code',
                        width: 130,
                    },
                    {
                        label: '类型',
                        prop: 'res_type',
                        width: 60,
                        formatter: (row) => {
                            let name = row.res_type;
                            $this.resTypeList.forEach((item) => {
                                if (item.code === row.res_type) {
                                    name = item.name;
                                }
                            });
                            return name;
                        }
                    },
                    {
                        label: '请求路径',
                        prop: 'target_url',
                    },
                    {
                        label: '权限标识',
                        prop: 'permission',
                    },
                    {
                        label: '状态',
                        prop: 'state',
                        width: 60,
                        align: 'center',
                        formatter: (row) => {
                            if (row.state === 1) {
                                return '有效';
                            } else if (row.state === -1) {
                                return '无效';
                            }
                            return '';
                        }
                    },
                    {
                        label: '排序',
                        prop: 'sn',
                        width: 60,
                    },
                    {
                        label: '创建时间',
                        prop: 'create_date',
                        width: 140,
                    }
                ],
                operates: {
                    width: 80,
                    fixed: 'right',
                    list: [ {
                        id: 'edit',
                        type: 'success',
                        icon: 'fa fa-pencil',
                        size: 'mini',
                        show: true,
                        tooltip: {
                            content: "编辑",
                        },
                        permission: 'res_add',
                        method: (index, row) => {
                            $this.openDialog(row);
                        }
                    }, {
                        id: 'del',
                        type: 'danger',
                        icon: 'fa fa-trash-o',
                        size: 'mini',
                        show: true,
                        filter(row){
                            return  row.pre_set == 0;
                        },
                        tooltip: {
                            content: "删除",
                        },
                        permission: 'res_del',
                        method: (index, row) => {
                            $this.deleteResource(row);
                        }
                    } ],
                },
                pagination: {
                    pageIndex: 1
                }
            },
            componentDialogOption: {
                visible: false,
            },
        };
    },
    computed: {
        ...mapState('system', [ 'resTypeList' ]),
    },
    mounted() {
        this.initZTree();
    },
    methods: {
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        initZTree() {
            let $this = this;
            $this.zTreeData = [];
            $this.zTreeData.push($this.root);
            let queryData = { parent_sd: '-1' };
            sysResourceApi.findSysResourceTree(queryData, result => {
                $this.resourceTreeData = result.data;
                let resetData = $this.resetTreeData(result.data);
                $this.resourceTree = [ { id: '-1', text: '根节点', children: resetData, _expanded: true, opened: true } ];
                let list = sysResourceApi.transferZTreeData(result.data, true);
                list.forEach(item => {
                    $this.zTreeData.push(item);
                });
                $this.setZTreeCheckData($this.zTreeData, $this.parentId);
                let setting = $.extend($this.ztreeSetting, {
                    check: {
                        enable: true,
                        chkStyle: 'radio',
                        radioType: 'all'
                    },
                    callback: {
                        onCheck: function (event, treeId, treeNode) {
                            $this.parentId = treeNode.id;
                            $this.setZTreeCheckData($this.zTreeData, treeNode.id);
                            $this.getList();
                        },
                        onClick: function (e, treeId, treeNode, clickFlag) {
                            if (!treeNode.checked) {
                                $this.parentId = treeNode.id;
                                zTree.checkNode(treeNode, !treeNode.checked, true);
                                $this.setZTreeCheckData($this.zTreeData, treeNode.id);
                                $this.getList();
                            }
                        }
                    }
                });
                let zTree = $.fn.zTree.init($("#resourceTree"), setting, $this.zTreeData);
                let node = zTree.getNodeByParam('id', '-1', null);
                zTree.expandNode(node, true);
                $this.getList();
            });
        },
        setZTreeCheckData: function (list, checkData) {
            if (checkData instanceof Array) {
                list.forEach(item => {
                    if (item.checked) {
                        item.checked = false;
                    }
                    if ($.inArray(item.id, checkData) !== -1) {
                        item.checked = true;
                    }
                });
            } else {
                list.forEach(item => {
                    if (item.checked) {
                        item.checked = false;
                    }
                    if (item.id === checkData) {
                        item.checked = true;
                    }
                });
            }
        },
        resetTreeData(list) {
            let $this = this;
            if (list && list.length > 0) {
                let data = [];
                list.forEach(item => {
                    let obj = {};
                    obj.id = item.sid;
                    obj.text = item.name;
                    obj.opened = true;
                    if (item.childrens && item.childrens.length > 0) {
                        let childs = $this.resetTreeData(item.childrens);
                        if (childs.length > 0) {
                            obj.children = childs;
                        }
                    }
                    if (item.res_type !== 'button') {
                        data.push(obj);
                    }
                });
                return data;
            } else {
                return [];
            }
        },
        getList(init) {
            let $this = this;
            $this.resourceList = [];
            if (init) {
                $this.tableOptions = $this.resetTablePagination($this.tableOptions);
            }
            let queryData = $this.getQueryParams($this.tableOptions, $this.searchForm);
            queryData.parent_sid = $this.parentId;
            $this.fetchData($this.$api.API_FindSysResources, queryData).then(result => {
                $this.resourceList = result.data || [];
                $this.tableOptions = $this.setTableTotal($this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selection = event.value;
            }
        },
        openDialog(row) {
            const _this = this;
            let title = '编辑资源';
            if (!row) {
                title = '新增资源';
                row = {
                    parent_sid: this.parentId,
                    res_type: 'application',
                    state: 1,
                };
            }
            _this.openComponentDialog({
                width: '640px',
                title,
                component: ResourceForm,
                propsData: {
                    row,
                    resourceTree: _this.resourceTreeData,
                },
                callback() {
                    _this.getList();
                },
            });
        },
        deleteResource(row) {
            let $this = this;
            $this.$confirm('将物理删除该资源，数据无法恢复，是否确认要删除?', '温馨提示', {
                cancelButtonClass: 'btn-custom-cancel',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let subData = { id: row.id };
                sysResourceApi.deleteSysResource(subData, () => {
                    $this.$message.success('删除成功！');
                    $this.getList();
                });
            });
        },
        moveDialog() {
            const _this = this;
            if (!_this.checkSelection(_this.selection, true)) {
                return;
            }
            _this.openComponentDialog({
                visible: true,
                width: '400px',
                title: '移动资源',
                component: MoveResource,
                propsData: {
                    selection: _this.selection,
                    treeData: _this.resourceTreeData,
                },
                callback() {
                    _this.initZTree();
                },
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.box-card {
    .searchForm {
        .el-form-item--mini.el-form-item,
        .el-form-item--small.el-form-item {
            margin-bottom: 0;
        }
    }
}
</style>
